import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import postcssPresetEnv from "postcss-preset-env";
import { createViteLicensePlugin } from "rollup-license-plugin";
import { nodePolyfills } from "vite-plugin-node-polyfills";
import { execSync } from "node:child_process";
import { readFileSync } from "node:fs";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";

dayjs.extend(utc);

// https://vitejs.dev/config/
export default defineConfig({
  define: {
    __VERSION__: JSON.stringify(
      JSON.parse(readFileSync("./package.json"))?.version ?? "",
    ),
    __HASH__: JSON.stringify(
      execSync("git rev-parse HEAD")?.toString().trim() ?? "",
    ),
    __SHORT_HASH__: JSON.stringify(
      execSync("git rev-parse --short HEAD")?.toString().trim() ?? "",
    ),
    __BUILD_TIME__: JSON.stringify(
      dayjs.utc().utcOffset(8).format("YYYY-MM-DD HH:mm:ss"),
    ),
  },
  plugins: [
    nodePolyfills({
      include: [
        "path",
        "os",
        "url",
        "fs",
        "stream",
        "util",
        "buffer",
        "global",
        "process",
        "events",
      ],
      overrides: {
        fs: "memfs",
      },
      protocolImports: true,
    }),
    react(),
    createViteLicensePlugin({
      replenishDefaultLicenseTexts: true,
    }),
  ],
  base: "./",
  css: {
    postcss: {
      plugins: [postcssPresetEnv()],
    },
  },
  build: {
    reportCompressedSize: false,
    rollupOptions: {
      output: {
        hashCharacters: "base36",
        manualChunks: {
          mdui: ["mdui"],
          vendor: ["copy-rich-text", "fast-base64", "lzma-js-simple-v2"],
          react: [
            "react",
            "react-dom",
            "react-router",
            "@react-hook/debounce",
            "@react-hook/event",
          ],
          highlight: ["react-syntax-highlighter", "prettier"],
          html_min: ["html-minifier-terser"],
          css_min: ["postcss", "cssnano"],
        },
      },
    },
  },
});
